﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ODataServicesDirectoryModel;
using System.Data.Services.Client;
using System.Collections.Specialized;

namespace SL_OData_Explorer
{
    public partial class UserFirstStartSplashxaml : ChildWindow
    {
        private bool IsPublicODataServiceListShown;
        public string publicServiceDirectoryUri = "http://PhanaticSL4/ODataServiceDirectory/ODataServiceDirectory.svc/";
        DataServiceCollection<DataService> dataServicesCollection;
        private ODataServicesDirectoryEntities serviceDirectoryContext;
        public UserFirstStartSplashxaml()
        {
            InitializeComponent();

        }
        public DataService SelectedService
        {
            get
            {
                if (lbPublicODataServices.SelectedItem != null)
                {
                    return lbPublicODataServices.SelectedItem as DataService;
                }
                return null;
            }
        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {

            if (!IsPublicODataServiceListShown && rdBrowsePublic.IsChecked.HasValue && rdBrowsePublic.IsChecked.Value)
            {
                IsPublicODataServiceListShown = true;
                DownloadPublicServiceDescriptions();
                BrowsePublicODataServicesAnimation.Begin();
            }
            else if (IsPublicODataServiceListShown)
            {
                this.DialogResult = true;
            }
            else
            {
                this.DialogResult = true;
            }
        }

        private void DownloadPublicServiceDescriptions()
        {
            serviceDirectoryContext = new ODataServicesDirectoryEntities(new Uri(publicServiceDirectoryUri));
            dataServicesCollection = new DataServiceCollection<DataService>(serviceDirectoryContext);

            lbPublicODataServices.ItemsSource = dataServicesCollection;
            dataServicesCollection.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(dataServicesCollection_LoadCompleted);
            dataServicesCollection.LoadAsync(serviceDirectoryContext.DataServices);
        }

        void dataServicesCollection_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.ToString());
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
    }
}

